package cs2340.flyingkiwi.todoapp;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * This class provides an access to the SQLite database for items.
 * 
 * @author Group Flying Kiwi
 * @version 15 Mar 2012
 * 
 * It provides several key operations to communicate with the database.
 * It is almost identical to the ToDoAppDbAdapter class.
 */

public class ItemAdapter {
	public static final String KEY_ITEM_TITLE = "item_title";
	public static final String KEY_ITEM_DESCRIPTION = "item_description";
	public static final String KEY_ITEM_LOCATION = "item_location";
	public static final String KEY_ITEM_DUEDATE = "item_duedate";
	public static final String KEY_ITEM_ROWID = "_id";
	
	private static final String TAG = "ToDoAppDbAdapter";
	
	private ItemDbHelper mItemDbHelper;
	private SQLiteDatabase mItemDb;
	
	private static final String DATABASE_ITEM_CREATE = 
			"create table item_table (_id integer primary key autoincrement, " +
			"item_title text not null, item_description text not null, " + 
			"item_location text not null, item_duedate text not null);";
	
	private static final String DATABASE_NAME = "data1";
	private static final String DATABASE_ITEM_TABLE = "item_table";
	private static final int DATABASE_VERSION = 2;
	
	private final Context mCtx;
	
	/**
	 * This private inner class actually makes the database and table
	 * by executing raw query.
	 */
	
	private static class ItemDbHelper extends SQLiteOpenHelper {
		ItemDbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_ITEM_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS item_table");
            onCreate(db);
        }
	}
	
	/**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
	public ItemAdapter(Context ctx){
		this.mCtx = ctx;
	}
	
	/**
     * Open the item database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
	public ItemAdapter open() throws SQLException {
        mItemDbHelper = new ItemDbHelper(mCtx);
        mItemDb = mItemDbHelper.getWritableDatabase();
        return this;
    }

	/**
	 * Close any open database object.
	 */
    public void close() {
       mItemDbHelper.close();
    }
    
    /**
     * Create a new item using the data provided. If the item is
     * successfully created return the new rowId for that item, otherwise return
     * a -1 to indicate failure.
     * 
     * @param title the title of the item
     * @param description the description of the item
     * @param location the location of the item
     * @param duedate the duedate of the item
     * @return rowId or -1 if failed
     */
    public long createItem(String title, String description, String location, String duedate){
    	ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_ITEM_TITLE, title);
        initialValues.put(KEY_ITEM_DESCRIPTION, description);
        initialValues.put(KEY_ITEM_LOCATION, location);
        initialValues.put(KEY_ITEM_DUEDATE, duedate);
        
        return mItemDb.insert(DATABASE_ITEM_TABLE, null, initialValues);
    }
    
    /**
     * Delete the item with the given rowId
     * 
     * @param rowId id of item to delete
     * @return true if deleted, false otherwise
     */
    public boolean deleteItem(long rowId) {
        return mItemDb.delete(DATABASE_ITEM_TABLE, KEY_ITEM_ROWID + "=" + rowId, null) >= 0;
    }
    
    /**
     * Return a Cursor over the list of all items in the database
     * 
     * @return Cursor over all items
     */
    public Cursor fetchAllItems() {

        return mItemDb.query(DATABASE_ITEM_TABLE, new String[] {KEY_ITEM_ROWID, KEY_ITEM_TITLE, KEY_ITEM_DESCRIPTION,
        		KEY_ITEM_LOCATION, KEY_ITEM_DUEDATE}, null, null, null, null, null);
    }
    
    /**
     * Return a Cursor positioned at the item that matches the given rowId
     * 
     * @param rowId id of item to retrieve
     * @return Cursor positioned to matching item, if found
     * @throws SQLException if item could not be found/retrieved
     */
    public Cursor fetchItem(long rowId) throws SQLException {

        Cursor mCursor =

            mItemDb.query(true, DATABASE_ITEM_TABLE, new String[] {KEY_ITEM_ROWID,
                    KEY_ITEM_TITLE, KEY_ITEM_DESCRIPTION, KEY_ITEM_LOCATION, KEY_ITEM_DUEDATE}, 
                    KEY_ITEM_ROWID + "=" + rowId, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }
    
    /**
     * Update the item using the details provided. The item to be updated is
     * specified using the rowId, and it is altered to use the title and body
     * values passed in
     * 
     * @param rowId id of item to update
     * @param title the title of the item
     * @param description the description of the item
     * @param location the location of the item
     * @param duedate the duedate of the item
     * @return true if the item was successfully updated, false otherwise
     */
    public boolean updateItem(long rowId, String title, String description, String location, String duedate) {
        ContentValues args = new ContentValues();
        args.put(KEY_ITEM_TITLE, title);
        args.put(KEY_ITEM_DESCRIPTION, description);
        args.put(KEY_ITEM_LOCATION, location);
        args.put(KEY_ITEM_DUEDATE, duedate);
        
        return mItemDb.update(DATABASE_ITEM_TABLE, args, KEY_ITEM_ROWID + "=" + rowId, null) >= 0;
    }
	
}
